package com.nullpointer.xchatfinal.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.nullpointer.xchatfinal.MainActivity;
import com.nullpointer.xchatfinal.R;
import com.nullpointer.xchatfinal.adapter.FriendsAdapter;
import com.nullpointer.xchatfinal.object.Friend;
import com.nullpointer.xchatfinal.object.PrivateMessageContent;
import com.nullpointer.xchatfinal.object.User;
import com.nullpointer.xchatfinal.object.MessageContent.MsgType;
import com.nullpointer.xchatfinal.service.ChatService;
import com.nullpointer.xchatfinal.utils.Common;
import com.nullpointer.xchatfinal.utils.DataManager;
import com.nullpointer.xchatfinal.utils.KiraGameLog;
import com.nullpointer.xchatfinal.utils.Utils;
import com.quickblox.core.Consts;
import com.quickblox.core.QBEntityCallbackImpl;
import com.quickblox.core.request.QBPagedRequestBuilder;
import com.quickblox.core.request.QBRequestGetBuilder;
import com.quickblox.customobjects.QBCustomObjects;
import com.quickblox.customobjects.model.QBCustomObject;
import com.quickblox.users.QBUsers;
import com.quickblox.users.model.QBUser;

public class FriendsFragment extends Fragment {

	private ListView lvUsers;
	private List<Friend> userData = new ArrayList<Friend>();
	private FriendsAdapter friendsAdapter;
	private int currentPageRequest = 1;
	private int page = 1;

	public static FriendsFragment newInstance() {
		FriendsFragment f = new FriendsFragment();
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_friends, container,
				false);
		findViewIds(view);
		init();
		setEvent();
		return view;
	}

	private void init() {
		friendsAdapter = new FriendsAdapter(getActivity(), userData);
		lvUsers.setAdapter(friendsAdapter);
		refreshData();
	}

	private void getFriendsUser() {
		showLoadingAnimation();
		QBRequestGetBuilder requestBuilder = new QBRequestGetBuilder();
		requestBuilder.setPagesLimit(1);
		requestBuilder.eq(Common.FriendsObject.USER_ID, DataManager
				.getInstance(getActivity()).getCurrentUser().getUserID());

		QBCustomObjects.getObjects(Common.FriendsObject.FRIENDS_CLASS,
				requestBuilder,
				new QBEntityCallbackImpl<ArrayList<QBCustomObject>>() {

					@Override
					public void onSuccess(
							ArrayList<QBCustomObject> customObjects,
							Bundle params) {
						KiraGameLog.d(">>> custom objects: " + customObjects);
						if (customObjects.size() == 0) {
							// No friend
							showNoFriends();
						} else {
							QBCustomObject object = customObjects.get(0);
							Object frObject = object.getFields().get(
									Common.FriendsObject.LIST_FRIENDS);
							if (frObject == null) {
								// No friend
								showNoFriends();
								return;
							}
							String friends = frObject.toString();
							if (friends != null) {
								String[] array = friends.split("/");
								Set<String> list = new HashSet<>();
								Collections.addAll(list, array);
								getUsersByIds(list);
							} else {
								// No friend
								showNoFriends();
							}

						}

					}

					@Override
					public void onError(List<String> errors) {
						KiraGameLog.d("getReportUser error " + errors);
						hideLoadingAnimation();
					}
				});

	}

	protected void showNoFriends() {
		hideLoadingAnimation();
		showNoFriendInfo();
	}

	protected void getUsersByIds(Set<String> usersIds) {
		QBPagedRequestBuilder pagedRequestBuilder = new QBPagedRequestBuilder();
		pagedRequestBuilder.setPage(page);
		pagedRequestBuilder.setPerPage(100);
		Set<Integer> listFriendIds = new HashSet<Integer>();
		for (String string : usersIds) {
			listFriendIds.add(Integer.parseInt(string));
		}

		QBUsers.getUsersByIDs(listFriendIds, pagedRequestBuilder,
				new QBEntityCallbackImpl<ArrayList<QBUser>>() {
					@Override
					public void onSuccess(ArrayList<QBUser> users, Bundle params) {
						if (users == null || users.size() == 0) {
							hideLoadingAnimation();
						} else {
							for (QBUser user : users) {
								Friend friend = new Friend();
								friend.setUser(Utils.convertQBUserToUser(user));
								userData.add(friend);
								sendCheckFriendsOnline(Integer.toString(user
										.getId()));
							}
							friendsAdapter.notifyDataSetChanged();
							int totalEntries = params
									.getInt(Consts.TOTAL_ENTRIES);
							currentPageRequest = params
									.getInt(Consts.CURR_PAGE);
							int perPage = params.getInt(Consts.PER_PAGE);
							int totalPage = (totalEntries / perPage) + 1;

							KiraGameLog.d("totalEntries: " + totalEntries
									+ " currentPageRequest "
									+ currentPageRequest + " totalPage "
									+ totalPage + " data size "
									+ userData.size());

							hideLoadingAnimation();
						}
					}

					@Override
					public void onError(List<String> errors) {
						KiraGameLog.d(">>> get nearby user error:" + errors);
						hideLoadingAnimation();
					}

				});
	}

	private void sendCheckFriendsOnline(String toUser) {
		PrivateMessageContent privateMessageContent = new PrivateMessageContent(
				getActivity(), "", MsgType.CHECK_FRIEND_ONLINE, toUser);
		ChatService.getInstance().sendMessagePrivate(privateMessageContent,
				null);
	}

	public void updateOnlineStatusFriendList(String fromUserID) {
		Integer userID = Integer.parseInt(fromUserID);
		for (Friend friend : userData) {
			User user = friend.getUser();
			if (user.getUserID().equals(userID)) {
				friend.setOnline(true);
				friendsAdapter.notifyDataSetChanged();
				return;
			}
		}
	}

	public void refreshData() {
		page = 1;
		clearUserData();
		showLoadingInfo();
		getFriendsUser();
	}

	private void showNoFriendInfo() {
		try {
			((MainActivity) getActivity()).showInfo(
					"You have no friends in contact list", false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void showLoadingInfo() {
		try {
			((MainActivity) getActivity()).showInfo("loading data...", true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void setEvent() {
	}

	private void findViewIds(View view) {
		lvUsers = (ListView) view.findViewById(R.id.lv_users);
	}

	private void clearUserData() {
		userData.clear();
		friendsAdapter.notifyDataSetChanged();
	}

	public void showLoadingAnimation() {
		try {
			((MainActivity) getActivity()).startRefeshAnimation();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void hideLoadingAnimation() {
		try {
			((MainActivity) getActivity()).stopRefeshAnimation();
			((MainActivity) getActivity()).hideInfo();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// public void showSearchFriend() {
	// try {
	// final SearchFriendDialogFragment dialog = new
	// SearchFriendDialogFragment();
	// FragmentTransaction transaction = getActivity()
	// .getSupportFragmentManager().beginTransaction();
	// transaction.add(dialog, "SearchFriendDialogFragment");
	// transaction.commitAllowingStateLoss();
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }
}
